﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Drawing;
using FisheryPlatform.SiteConfig;
using FisheryPlatform.DataAccess.Passport;
using FisheryPlatform.Common;

namespace FisheryPlatform.Bussiness.Passport
{
    public class ValidateCodeManager
    {
        /// <summary>
        /// 生成验证码
        /// </summary>
        /// <param name="context"></param>
        public static void GenerateCode(HttpContext context)
        {
            #region
            string code = RandomUtility.ValidateCode();
            string guid = VerificationCodeDB.Insert(code);
            var cookieName = SiteConfigManager.AppSettings["CodeCookieName"].Value;
            HttpCookie codeCookie = context.Request.Cookies[cookieName];
            if (codeCookie == null)
            {
                codeCookie = new HttpCookie(cookieName);
                codeCookie.Domain = SiteConfigManager.AppSettings["CodeCookieDomain"].Value;
                codeCookie.Value = guid;
            }
            else
            {
                codeCookie.Domain = SiteConfigManager.AppSettings["CodeCookieDomain"].Value;
                codeCookie.Value = guid;
            }
            context.Response.Cookies.Add(codeCookie);
            var buffer = ImageUtility.ValidateCode(code);
            context.Response.OutputStream.Write(buffer, 0, buffer.Length);
            #endregion
        }

        /// <summary>
        /// 验证验证码输入是否正确
        /// </summary>
        /// <param name="page"></param>
        /// <param name="codeValue"></param>
        /// <returns>true为通过验证,false为未通过验证</returns>
        public static bool Validate(string codeValue)
        {
            #region
            bool result = false;
            string cookieName = SiteConfigManager.AppSettings["CodeCookieName"].Value;
            System.Web.HttpCookie hc = System.Web.HttpContext.Current.Request.Cookies[cookieName];
            if (hc != null)
            {
                result = VerificationCodeDB.Validate(new Guid(hc.Value), codeValue);
            }
            else
            {
                result = false;
            }

            return result;
            #endregion
        }
    }
}
